package com.shujia.gensql

import java.io.FileWriter

import scala.collection.mutable.ListBuffer
import scala.io.Source

object GenSql {
  def main(args: Array[String]): Unit = {
    /**
      * 在原本的建表语句上增加预留字段
      * 去掉分区字段
      * 在表名上增加标识
      *
      */

    val newDDlSql = new ListBuffer[String]


    val yuField: String =
      """
        |,f1 string comment '预留字段',
        |f2 string comment '预留字段'
        |
        """.stripMargin


    //1、读取sql文件
    val sqlStr: String = Source.fromFile("data/sql.sql").getLines().toList.mkString("\n")

    //2、按照分号拆分
    val list: List[String] = sqlStr.split(";").toList
    for (ddlSql: String <- list) {

      //查找括号开始和接收位置
      val fieldStart: Int = ddlSql.indexOf("(") + 1
      val fieldEnd: Int = ddlSql.indexOf(")")

      //截取列
      val fields: String = ddlSql.substring(fieldStart, fieldEnd)

      //增加预留字段
      val mergeField: String = fields + yuField


      //取出表除了分区后面所有的信息

      val rowStaart: Int = ddlSql.indexOf("ROW")
      val info: String = ddlSql.substring(rowStaart)


      //取出表名
      val tableName: String = ddlSql.substring(ddlSql.indexOf(".") + 1, ddlSql.indexOf("("))
      println(tableName)

      //拼接完整sql


      val newDDL: String =
        s"""
           |CREATE external TABLE IF NOT EXISTS  ods.${tableName.trim}_f {
           |${mergeField.trim}
           ) ${info.trim}
           |
        """.stripMargin


      newDDlSql.append(newDDL)
    }


    //将sql保存
    val writer = new FileWriter("data/new_ddl.sql")
    writer.write(newDDlSql.mkString(";\n"))
    writer.close()
  }
}
